package org.mq.mymq.broker.netty.broker;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.mq.mymq.broker.cache.CommonCache;
import org.mq.mymq.common.coder.TcpMsgDecoder;
import org.mq.mymq.common.coder.TcpMsgEncoder;
import org.mq.mymq.common.constants.TcpConstants;
import org.mq.mymq.common.event.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName BrokerServer
 * @Description
 * @Author jiarong_ye
 * @Date 2025/6/27 13:01
 * @Version 1.0
 */
public class BrokerServer {
    private static final Logger log = LoggerFactory.getLogger(BrokerServer.class);
    private int port;

    public BrokerServer(int port) {
        this.port = port;
    }

    /**
     * 启动服务端程序
     *
     * @throws InterruptedException
     */
    public void startServer() throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel channel) throws Exception {
                ByteBuf delimiter = Unpooled.copiedBuffer(TcpConstants.DEFAULT_DECODE_CHAR.getBytes());
                channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 8, delimiter));
                channel.pipeline().addLast(new TcpMsgDecoder());
                channel.pipeline().addLast(new TcpMsgEncoder());
                channel.pipeline().addLast(new BrokerServerHandler(new EventBus("broker-server-handler-")));
            }

        });
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            CommonCache.getCommitLogMMapFileModelManager().getmMapFileModelMap().values().forEach(c -> c.clean());
            CommonCache.getConsumerQueueMMapFileModelManager().getConsumerQueueMMapFileModels().values().forEach(list -> list.forEach(q -> q.clean()));
            log.info("my mq broker is shutting down");
        }));
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        log.info("my mq broker is listening on port " + port);
        channelFuture.channel().closeFuture().sync();
    }
}
